<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-05-02
 * Time: 16:54
 */

namespace app\api\service;


use app\admin\model\Cmdlog;
use app\admin\model\Roomclean;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptable;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;

class TableService
{

    public $openCmdUrl = "http://47.97.67.38:8080/cmd/open";

    public $tqV3CmdUrl = "http://47.97.67.38:8881/qx/openTable";
    public $openTqCmdUrl = "http://47.97.67.38:8080/cmd/testTq";

    public function updateTableClose($order, $device)
    {
        $req = array();
        $req['sec'] = 0;
        $req['orderId'] = 3;
        $req['deviceSn'] = $device['device_sn'];

        $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
        $ret = json_decode($ret, true);
        if ($ret['code'] == 0) {
            $msg = "正在打开中";
        }
        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);
    }

    public function close($order, $device)
    {

        $req = array();
        if ($device['version'] == 1) {
            $req = array();
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        } else if ($device['version'] == 2) {
            $req = array();
            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }

        } else if ($device['version'] == 3) {
            $req = array();
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];

            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

    }

    public function open($order, $device)
    {

        if ($order['status'] != 'doing') {

            error_log("====订单号开台不正常=====" . json_encode($order));
            return;
        }

        //需要判断订单剩余多长时间
        $useTime = time() - $order['book_start'];
        $newTime = $order['min'] * 60 - $useTime;

        $req = array();
        if ($device['version'] == 1) {
            $req = array();
            $req['switchOne'] = 1;
            $req['switchTwo'] = 1;
            $req['door'] = 1;
            $req['hello'] = "您好开台成功祝您玩得开心";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }

        } else if ($device['version'] == 2) {
            $req = array();
            $req['sec'] = $newTime;
            $req['voice'] = "您好开台成功,祝您玩得开心";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }

        } else if ($device['version'] == 3) {
            $req = array();
            $req['sec'] = $newTime;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];

            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

    }

    //关台时，计费
    public function overCount($st, $et, $rules)
    {
        // 解析时间段和费率
        $timeSegments = [];
        foreach ($rules as $key => $value) {
            if (strpos($key, 'time') !== false) {
                list($start, $end) = explode('~', $value);
                $priceKey = str_replace('time', 'price', $key);
                $timeSegments[] = [
                    'start' => $start,
                    'end' => $end,
                    'price' => floatval($rules[$priceKey])
                ];
            }
        }

        // 计算总费用
        $totalCost = 0;
        $currentTimestamp = $et;
        $count_st_time = $st;
        $is_real = false;
        while ($currentTimestamp > $count_st_time) {
            $currenDate = date('Y-m-d', $count_st_time);
            foreach ($timeSegments as $timeSegment) {
                $area_st = strtotime($currenDate . " " . $timeSegment['start']);
                $area_et = strtotime($currenDate . " " . $timeSegment['end']);
                if ($area_st > $area_et) {
                    if (!$is_real) {
                        $area_st -= 86400;
                        $is_real = true;
                    } else {
                        $area_et += 86400;
                    }
                }

                //判断订单开始时间是否在该区域
                if ($area_st <= $count_st_time && $count_st_time <= $area_et) {
                    if ($et <= $area_et) {//订单结束时间也在该时间区域
                        //计费,按分钟计费
                        if($area_st >= $st){
                            $totalCost += ($et - $area_st) / 3600 * $timeSegment['price'];
                        }else{
                            $totalCost += ($et - $st) / 3600 * $timeSegment['price'];
                        }
                        $count_st_time = $area_et + 1;
                        break;
                    } else {
                        //计算该区域的收费
                        $totalCost += ($area_et - $count_st_time) / 3600 * $timeSegment['price'];
                        $count_st_time = $area_et;
                    }
                }
            }
        }
        return formatMoney($totalCost);
    }

    //获取会员最大的开台时长
    public function getDuration($startTime, $balance, $rules)
    {
        // 解析时间段和费率
        $periods = [];
        foreach ($rules as $key => $value) {
            if (strpos($key, 'time') !== false) {
                list($start, $end) = explode('~', $value);
                $priceKey = str_replace('time', 'price', $key);
                $periods[] = [
                    'start' => strtotime($start),
                    'end' => strtotime($end),
                    'price' => floatval($rules[$priceKey]) / 60 // 每分钟费用
                ];
            }
        }

        // 初始化变量
        $minutesAvailable = 0;
        $currentBalance = $balance;

        // 循环计算直到余额耗尽
        $is_real = false;
        while ($currentBalance > 0) {
            foreach ($periods as $period) {
                // 处理跨天的情况
                if ($period['start'] > $period['end']) {
                    if (!$is_real) {
                        $period['start'] -= 86400; // 开始时间减一天
                        $is_real = true;
                    } else {
                        $period['end'] += 86400; // 加一天的秒数
                    }
                }

                // 确定当前时间段的结束时间
                $periodStartTimestamp = $period['start'];
                $periodEndTimestamp = $period['end'];

                // 如果开始时间在当前时间段内
                if ($startTime >= $periodStartTimestamp && $startTime < $periodEndTimestamp) {
                    // 计算用户在该时段需要消费的金额,余额低于需要消费的金额则跳出
                    $consumeAmount = $period['price'] * (($periodEndTimestamp - $startTime) / 60);
                    if ($currentBalance <= $consumeAmount) {
                        $minutesAvailable += $currentBalance / $period['price'];
                        $currentBalance = 0.00;
                        break;
                    } else {
                        $minutesAvailable += $consumeAmount / $period['price'];
                        $currentBalance -= $consumeAmount;
                        $startTime = strtotime(date('H:i', $periodEndTimestamp));
                    }
                }
            }
        }
        return floor($minutesAvailable);
    }

    public function cacFee($book_end, $book_start, $rule)
    {
        $minute = floor(($book_end - $book_start) % 86400 / 60);
        $hour = ceil($minute / 60);
        $start = date("H", $book_start);


        $time1 = explode("~", $rule['time1']);
        if (count($time1) == 1) {
            $startTime1 = explode("-", $rule['time1'])[0];
            $endTime1 = explode("-", $rule['time1'])[1];
        } else {
            $startTime1 = explode("~", $rule['time1'])[0];
            $endTime1 = explode("~", $rule['time1'])[1];
        }
        $time2 = explode("~", $rule['time2']);
        if (count($time2) == 1) {
            $startTime2 = explode("-", $rule['time2'])[0];
            $endTime2 = explode("-", $rule['time2'])[1];
        } else {
            $startTime2 = explode("~", $rule['time2'])[0];
            $endTime2 = explode("~", $rule['time2'])[1];
        }
        $startTime1 = intval($startTime1);
        $endTime1 = intval($endTime1);


        $startTime2 = intval($startTime2);
        $endTime2 = intval($endTime2);
        $slots = array();

        if ($endTime1 < $startTime1) {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
        }

        if ($endTime2 < $startTime2) {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
        }

        $hour = floor($minute / 60);
        $amount = get_charge($start, $hour, $slots, $minute);

        return $amount;
    }


    public function updateTableFree($redis, $shop_id)
    {

        $room_key = "table_count_" . $shop_id;
        $shopTableModel = new Shoptable();
        $roomValue = $shopTableModel->where('shop_id', $shop_id)->where('status', 'free')->count('id');
        $redis->set($room_key, $roomValue);

    }

}